package com.qijian.maindata.tools.poi;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.qijian.common.utils.DictUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Objects;

@Slf4j
public class ExcelDictConvert implements Converter<String> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        log.info("convert to excel data :{},{}",value, JSONUtil.toJsonStr(contentProperty));
        Field field = contentProperty.getField();
        ExcelDictType excelDictType = field.getAnnotation(ExcelDictType.class);
        if(Objects.isNull(excelDictType)){
            return new WriteCellData<>(value);
        }
        String dictKey = excelDictType.type();
        if(StrUtil.isBlank(dictKey)){
            return new WriteCellData<>(value);
        }

        String dictValue = DictUtils.getDictLabel(dictKey, value);
        if(StrUtil.isNotBlank(dictValue)){
            value = dictValue;
        }
        return new WriteCellData<>(value);
    }

}
